package com.dlyk.controller;

import com.dlyk.bean.TUser;
import com.dlyk.query.UserQuery;
import com.dlyk.result.R;
import com.dlyk.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;;
import java.util.List;

/**
 * 用户登录接口
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取登录用户信息
     * @param authentication
     * @return
     */
    @GetMapping("/api/login/info")
    public R loginUser(Authentication authentication){
        TUser tUser= (TUser)authentication.getPrincipal();
        return R.OK(tUser);
    }

    /**
     * 免登录（自动登录）
     * @return
     */
    @GetMapping("/api/login/free")
    public R freeLogin(){
        return R.OK();
    }

    /**
     * 用户分页查询
     * @param current
     * @return
     */
    @GetMapping("/api/users")
    public R userPage(@RequestParam("current") Integer current){
        if (current==null){
            current=1;
        }
        PageInfo<TUser> pageInfo = userService.getUserByPage(current);
        return R.OK(pageInfo);
    }

    /**
     * 根据id查询用户信息
     * @param id
     * @return
     */
    @GetMapping("/api/user/{id}")
    public R userDetail(@PathVariable Integer id){
        TUser tUser=userService.getUserById(id);
        return R.OK(tUser);
    }

    /**
     * 新增用户
     * @param userQuery
     * @return
     */
    @PostMapping("/api/user")
    public R userSubmit(UserQuery userQuery,@RequestHeader("Authorization") String token){
        userQuery.setToken(token);
        int save=userService.saveUser(userQuery);
        return save >=1 ? R.OK() : R.FAIL();
    }

    /**
     * 更新用户信息
     * @param userQuery
     * @return
     */
    @PutMapping("/api/user")
    public R editUser(UserQuery userQuery,@RequestHeader("Authorization") String token){
        userQuery.setToken(token);
        int updated=userService.updateUser(userQuery);
        return updated >=1 ? R.OK() : R.FAIL();
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/api/user/{id}")
    public R delUser(@PathVariable Integer id){
        int del=userService.deleteUser(id);
        return del>0 ? R.OK(del) : R.FAIL();
    }

    /**
     * 批量删除用户
     * @return
     */
    @DeleteMapping("/api/user/")
    public R batchDelUser(@RequestParam String ids){
        List<String> list = Arrays.asList(ids.split(","));
        int users=userService.batchDelUser(list);
        return users >= list.size() ? R.OK(list) : R.FAIL();

    }

    /**
     * 查询负责人
     * @return
     */
    @GetMapping("/api/owner")
    public R selectOwner(){
        List<TUser> owner =userService.selectOwner();
        return R.OK(owner);
    }
}
